package com.kmu.lwl.imp.impl;

import com.kmu.lwl.entiy.Connection;
import com.kmu.lwl.entiy.Course;
import com.kmu.lwl.factory.HibernateFactory;
import com.kmu.lwl.imp.CourseDao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;


import java.util.ArrayList;
import java.util.List;

public class CourseDaoimpl implements CourseDao {
    @Override
    public List getStudentAllCourse(String studentNo) {
        Session session = HibernateFactory.getSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery("from Connection where studentId=?1").setParameter(1, studentNo);
        List list = (List) query.list();
        List<Object> list1 = new ArrayList<>();
        for(Object o:list){
            Connection o1 = (Connection) o;
            Query query1 = session.createQuery("from Course where id =?1").setParameter(1, o1.getCourseId());
            Course course = (Course) query1.uniqueResult();
            list1.add(course);
        }
        transaction.commit();
        session.close();
        return list1;
    }

    @Override
    public void chosenCourse(Connection connection) {
        Session session = HibernateFactory.getSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery("from Connection where studentId=?1 and courseId=?2").setParameter(1, connection.getStudentId()).setParameter(2, connection.getCourseId()).setMaxResults(1);
        Connection c = (Connection) query.uniqueResult();
        session.delete(c);
        transaction.commit();
        session.close();
    }

    @Override
    public List getAllCourse() {
        Session session = HibernateFactory.getSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery("from Course");
        List list = query.list();
        transaction.commit();
        session.close();
        return list;
    }
    public Boolean courseSelection(Connection connection) {
        Session session = HibernateFactory.getSession();
        Transaction transaction = session.beginTransaction();
        Boolean b;
        Query query = session.createQuery("from Connection where studentId=?1 and courseId=?2").setParameter(1, connection.getStudentId()).setParameter(2, connection.getCourseId()).setMaxResults(1);
        Connection c = (Connection) query.uniqueResult();
        if(c==null){
            session.save(connection);
            b=true;
        }else {
            b=false;
        }
        transaction.commit();
        session.close();
        return b;
    }
}
